package com.time.company.components.login;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.Gson;
import com.time.company.R;
import com.time.company.app.AddressManager;
import com.time.company.base.BaseActivity;
import com.time.company.components.MainActivity;
import com.time.company.servermodel.BasicBean;
import com.time.company.servermodel.User;
import com.time.company.utils.JpushUtils;
import com.time.company.utils.NetWorkUtils;
import com.time.company.utils.ToastUtils;
import com.time.company.views.PwdLayout;
import com.time.company.views.UserLayout;
import com.time.company.webserver.helper.WebServerManager;
import com.time.company.webserver.request.BasicRequest;
import com.time.company.webserver.request.requestsParamters.LoginParameters;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.Response;

/**
 * Login - company
 * Created by Bing on 2017/10/25.
 * E-mail is tx16bing@163.com
 */

public class LoginActivity extends BaseActivity implements View.OnClickListener {

    private static final int REGISTER_REQUEST_CODE = 102;

    private UserLayout account;
    private PwdLayout psd;
    private Button btnLogin;

    private TextView tvRegister, tvForget;
    private Request request;
    private static final int LOGIN_USER_WHAT = 22;
    private static final int USER_INFO_WHAT = 27;

    public static void start(Activity activity) {
        Intent intent = new Intent(activity, LoginActivity.class);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        assignViews();
        addListener();
    }

    private void assignViews() {
        account = findView(R.id.ll_user_name);
        psd = findView(R.id.ll_pwd);
        btnLogin = findView(R.id.btn_login);
        tvRegister = findView(R.id.tv_register);
        tvForget = findView(R.id.tv_forget_psd);
    }

    private void addListener() {
        btnLogin.setOnClickListener(this);
        tvRegister.setOnClickListener(this);
        tvForget.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.btn_login:
                if (!checkForm()) return;
                loginRequest();
                break;

            case R.id.tv_register:
                RegisterActivity.start(this, REGISTER_REQUEST_CODE);
                break;

            case R.id.tv_forget_psd:
                ForgetPsdActivity.start(this, getString(R.string.psd_forget_flag));
                break;

            default:
                break;
        }
    }

    private boolean checkForm() {
        boolean formIsValid = true;
        if (TextUtils.isEmpty(account.getUserName())) {
            ToastUtils.showShort(getString(R.string.please_input_telephone));
            formIsValid = false;
        } else if (TextUtils.isEmpty(psd.getPassword())) {
            ToastUtils.showShort(getString(R.string.please_input_psd));
            formIsValid = false;
        }

        return formIsValid;
    }

    /**
     * 登录
     */
    private void loginRequest() {
        if (NetWorkUtils.isNetAvailable(this)) {
            request = new BasicRequest(AddressManager.getInstance().getAddress());
            LoginParameters parameters = new LoginParameters();
            parameters.setCommand(getString(R.string.command_loginAppCompanyNormal));
            parameters.setAccountName(account.getUserName());
            parameters.setPassword(psd.getPassword());
            if (TextUtils.isEmpty(JpushUtils.getRegisterId(this))){
                parameters.setJpushId(getString(R.string.zero));
            }else {
                parameters.setJpushId(JpushUtils.getRegisterId(this));
            }
            request.add(getString(R.string.command), parameters.getCommand());
            request.add(getString(R.string.platform), parameters.getPlatform());
            request.add(getString(R.string.data), new Gson().toJson(parameters));
            request.setCancelSign(toString());
            WebServerManager.getInstance().add(this, request, this, LOGIN_USER_WHAT,
                    true, true, true);
        } else {
            ToastUtils.showShort(getString(R.string.network_error));
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {

            case REGISTER_REQUEST_CODE:
                if (resultCode == RESULT_OK)
                    finish();
                break;

            default:
                break;

        }
    }

    // 加载个人信息
    private void getUserInfo() {
        if (NetWorkUtils.isNetAvailable(this)) {
            request = new BasicRequest(AddressManager.getInstance().getAddress());
            LoginParameters parameters = new LoginParameters();
            parameters.setCommand(getString(R.string.command_getUserInfo));
            parameters.setUserId(application.getAccount());
            if (TextUtils.isEmpty(JpushUtils.getRegisterId(this))){
                parameters.setJpushId(getString(R.string.zero));
            }else {
                parameters.setJpushId(JpushUtils.getRegisterId(this));
            }
            request.add(getString(R.string.command), parameters.getCommand());
            request.add(getString(R.string.platform), parameters.getPlatform());
            request.add(getString(R.string.data), new Gson().toJson(parameters));
            request.setCancelSign(toString());
            WebServerManager.getInstance().add(this, request, this, USER_INFO_WHAT,
                    true, true, true);
        } else {
            ToastUtils.showShort(getString(R.string.network_error));
        }
    }

    @Override
    public void onSucceed(int what, Response<BasicBean> response) {

        BasicBean basicBean = response.get();
        if (basicBean == null) return;

        if (basicBean.isSuccess()) {
            if (what == LOGIN_USER_WHAT) {
                User user = basicBean.parseData(User.class);
                if (user == null) return;
                application.setAppInfo(user.getUserId(), account.getUserName(), true);
                getUserInfo();
            }else if (what == USER_INFO_WHAT){
                User user = basicBean.parseData(User.class);
                mVMcreator.setUserViewModel(user);
                MainActivity.start(this);
                finish();
            }
        } else {
            ToastUtils.showShort(basicBean.getMsg());
        }
    }
}
